import mx.utils.Delegate;

/**
	Creates a scrollbar for a text area.


	@author Chandler McWilliams
	@version 1.0
	@version 2005-07-01

**/
class timber.ui.control.TextScrollbar extends timber.ui.control.Slider
{

	private var target;
	private var timerid;
	private var scrollNeeded:Boolean;

	
	public function setHeight(val) { setSize(val); }

	public function setTarget(val) {
		target = val;
		setMin(1);
		setMax(val.maxscroll);
		update();
	}
	
	public function onChange(v) { target.scroll = v; }


	// if this returns true, the scrollbar sets the size top to match the top
	// and bottom of the textarea
	// should be overridden in subclasses
	private function dynamicallySetsPosition() {
		return true;
	}
	
	public function isScrollbarNeeded() {
		return scrollNeeded;
	}

	// setup
	public function update () {
		// ===========================================================
		// - POSITION SCROLLBAR ELEMENTS
		// ===========================================================
		if (dynamicallySetsPosition()) {
			this._y = target._y;
			upArrow._y = 0;
			downArrow._y = getSize()?getSize():target._height;
		}
		
		// determine size of the scrollbar if the handle is proportional
		if (handle.isProportional()) {
			var scrollDiff = target.bottomScroll/(target.bottomScroll + target.maxscroll);
			var newheight = Math.floor(((downArrow._y + downArrow._height) - (upArrow._y + upArrow._height)) * scrollDiff);
			handle.setHeight(newheight);
		}
		
		// initalization for new text
		updateAfterChange();
	
		// make a listener object
		var self = this;
		var textears = {
			// add a watch to update the position of the handle
			onScroller: function () {
				self.setValue(self.target.scroll);
			}
		}
		// add the listener
		target.removeListener(textears);
		target.addListener(textears);
	
		// watch for text changes
		target.watch("text",Delegate.create(this, changeWatch));

		// and again for htmltext
		target.watch("htmlText",Delegate.create(this, changeWatch));

		super.update();
	}

	function changeWatch (prop, oldval, newval) {
		// have to make a timer b/c flash is stupid
		var self = this;
		if (timerid) {
			clearInterval(timerid);
			delete(timerid);
		}
		
		timerid = setInterval(
			function() {
				clearInterval(self.timerid);
				delete(self.timerid);
				self.updateAfterChange();
			},
			40
		);
		return newval;
	}


	function updateAfterChange () {
		target.scroll = Math.min(target.maxscroll, target.scroll);				// reset scroll
		handle._y = handlemin;						// make sure handle is at the min
		// see if we should hide the scrollbar
		
		if (target.maxscroll > target.scroll) {
			scrollNeeded = true;
			show();
		} else {
			scrollNeeded = false;
			hide();
		}
		
		// update max
		setMax(target.maxscroll);

		clearInterval(timerid);
		delete(timerid);
	}
	
	public function show() {
		this._visible = true;
	}
	
	public function hide() {
		this._visible = false;
	}
}
